﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using BrainTechLLC.FolderExplorer;
using BrainTechLLC.WPF;
using BrainTechLLC;
using BrainTechLLC.ThreadSafeObjects;
using ImageAppDataModels;
using WpfImageDuplicates;
using System;

namespace WpfImageDuplicates
{
    public partial class DropFromListBoxToTreeViewCommand : RoutedCommand, ICommand
    {
        public void Execute(object data, ItemsControl src, UIElement droppedOnto)
        {
            IHasFileBackingStore vm = data as IHasFileBackingStore;
            ListBox lb = src as ListBox;
            Grid g = droppedOnto as Grid;
            FolderViewModel destFolder;

            if (g == null)
            {
                ListView lv = droppedOnto as ListView;

                if (lv == null)
                {
                    return;
                }

                destFolder = lv.Tag as FolderViewModel;
            }
            else
            {
                destFolder = g.DataContext as FolderViewModel;
            }

            ImageCollectionView collectionView = BrainTechLLC.WPF.TempExten.FindParent<ImageCollectionView>(src);

            if (collectionView != null)
            {
                collectionView.GetAllThumbnailViews().Where(vw => vw.FileImageViewModel.SelectedByUser).ForEach(vw =>
                {
                    try
                    {
                        ListBoxItem parent = BrainTechLLC.WPF.TempExten.FindParent<ListBoxItem>(vw);
                        parent.IsSelected = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                });
            }

            var sel = lb.GetSelected<IHasFileBackingStore>();

            if (!sel.Contains(vm))
            {
                sel.Add(vm);
            }

            for (int n = sel.Count - 1; n >= 0; n--)
            {
                var fvm = sel[n];

                if (fvm == null)
                    continue;

                string oldFolderMatch = Path.GetDirectoryName(fvm.FileName) + @"\";
                string newPath = fvm.FileName.Replace(oldFolderMatch, destFolder.FullPath + @"\");

                App.DataProvider.Move(fvm.FileName, newPath);                
                Window1.MainWindow.FileImageCollectionViewModels.ForEach(o=>o.RemoveByFileName(fvm.FileName));
            }

            destFolder.ClearFiles();
        }
    }
}
